package logic

import (
	"context"
	"github.com/google/uuid"
	"srv/model/mysql"
	"srv/pkg"
	"strconv"

	"srv/internal/svc"
	"srv/sesame"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *sesame.AddOrderRequest) (*sesame.AddOrderResponse, error) {
	g := mysql.Goods{}
	_, err := g.DetailGoods(int(in.GoodsId))
	if err != nil {
		logx.Error("获取商品详情失败:", err)
		return nil, err
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}

	if g.GoodsStock < 1 {
		logx.Error("商品库存不足")
		return nil, err
	}

	orderSn := uuid.NewString()

	o := mysql.Order{
		OrderSn:    orderSn,
		UserId:     int(in.UserId),
		Amount:     g.GoodsPrice,
		Status:     g.GoodsStock,
		Payment:    2,
		GoodsTitle: g.GoodsTitle,
		GoodsId:    int(g.ID),
		GoodsCover: g.GoodsCover,
	}

	err = o.AddOrder()
	if err != nil {
		logx.Error("创建订单失败", err)
		return nil, err
	}

	GoodsStock := g.GoodsStock - 1
	err = g.UpdateStock(GoodsStock)
	if err != nil {
		logx.Error("扣减库存失败", err)
		return nil, err
	}

	amount := strconv.FormatFloat(g.GoodsPrice, 'f', 2, 64)

	aliPay := pkg.NewAliPay()
	papURL := aliPay.Pay(g.GoodsTitle, orderSn, amount)
	return &sesame.AddOrderResponse{

		PayUrl: papURL,
	}, nil
}
